using CapHttp.Core;
using CapHttp.Demo.Shared.Events;

namespace CapHttp.Producer.Worker;

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IDistributedEventPublisher _eventPublisher;
    private int _count = Random.Shared.Next(10001, 99999);

    public Worker(ILogger<Worker> logger, IDistributedEventPublisher eventPublisher)
    {
        _logger = logger;
        _eventPublisher = eventPublisher;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            _count++;

            try
            {
                await _eventPublisher.PublishAsync(new Event1(12 + _count, $"Jack {_count}"));
                await _eventPublisher.PublishAsync(new Event2($"Tom {_count}", Random.Shared.Next(5, 89)));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "消息发送失败: {message}", ex.Message);
            }
            
            await Task.Delay(30000, stoppingToken);
        }
    }
}